var dbUtil = require('./dbUtil')

function update_out(outBill,callback) {

    var sql = "update stock\n" +
        " set quantity = quantity -"+outBill.quantity+"\n" +
         "  where product_id = "+outBill.product_id;

    dbUtil.query(sql,null,function (err,result) {
        if(result.affectedRows>0){
            callback(true);
        }else {
            callback(false)
        }
    })
}


function select(query,callback) {
    var sql = "select s.stock_id, p.*,s.quantity from stock  s\n" +
        "inner join product p\n" +
        "on s.product_id = p.product_id where 1=1\n";
    var params = [];

 //   query.productName = '商品';  // '%商品%'
    if(query.productName){
        sql += " and p.product_name like ?"
        params.push('%'+query.productName+'%');

    }
    if(query.model){
        sql += " and p.model like ?"
        params.push('%'+query.model+'%');
    }
    if(query.unit){
        sql += " and p.unit like ?"
        params.push('%'+query.unit+'%');
    }

    dbUtil.query(sql, params, function (err, rows) {
        rows = rows.map(toStock)
         /*rows = rows.map(function (row) {
            return {
                stock_id:row.stock_id,
                product:{
                    product_id:row.product_id,
                    product_name:row.product_name,
                    model:row.model,
                    unit:row.unit
                },
                quantity:row.quantity
            }
        })*/
       callback(err,rows)
    })
}

var toStock = function (row) {
    return {
        stock_id:row.stock_id,
        product:{
            product_id:row.product_id,
            name:row.product_name,
            model:row.model,
            unit:row.unit
        },
        quantity:row.quantity
    }
}

module.exports = {
    select,
    update_out
}